<?php
/**
 * sqlite数据库架构处理类
 *
 * @author Mo yi <root@imoi.cn>
 * @link   http://www.imoi.cn
 * @copyright Copyright &copy; 2010-2012 DuoLam Software LLC
 * @license http://www.imoi.cn/license/
 * @version $Id: dpSqliteSchema.php 2799 2012-04-10 09:31:13Z Mo.yi $
 * @package db.schema
 * @since 1.0
 */

class dpSqliteSchema extends dpSchema implements ISchema
{    
	/**
	 * 主键
	 */
	protected $_pk;

	/** 
     * 字段类型
     */
	public $columnType = array
	(
        'pk'       => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
        'string'   => 'varchar(255)',
        'text'     => 'text',
        'integer'  => 'integer',
        'int_not'  => 'integer NOT NULL DEFAULT 0',
        'float'    => 'float',
        'datetime' => 'datetime',
        'time'     => 'time',
        'date'     => 'date',
        'binary'   => 'blob',
        'boolean'  => 'tinyint(1)',
        'bool_not' => 'tinyint(1) NOT NULL DEFAULT 0',
    );

	/**
     * 获取表字段信息
     * @param string $table 表名
     * @return array  字段信息列表
     */
	public function getColumn($table)
	{
		$caching = (int)D::$config['component']['db']['schema_caching'];
		$sql = 'PRAGMA table_info(' . $table .')';
		$rs  = $this->connect->finds($sql, $caching);

		if (empty($rs))
			return false;
		else {
			foreach ($rs as $k => $v) {
				$columns[$k]['name']    = $v['name'];
				$columns[$k]['type']    = $v['type'];
				$columns[$k]['default'] = $v['dflt_value'];

				if ($v['pk']) {
					$columns[$k]['pk']  = true;
                    $columns[$k]['auto']= true;
                    $this->_pk = $v['name'];
				}
			}

			return $columns;
		}
	}

	/**
	 * 获取表主键名称
	 * @return string 主键名字
	 */
	public function getPk()
	{
		return !empty($this->_pk) ? $this->_pk : false;
	}

	/**
	 * 获取重命名表的SQL语句
	 * @param string $name    表名称
	 * @param string $newName 表新名称
	 * @return string 返回重命名表的SQL语句
	 */
	public function getRenameTableString($name, $newName)
	{
		return 'ALTER TABLE `' . $name .'` RENAME TO `' . $newName . '`';
	}
	
	/**
	 * 获取清空数据表的SQL语句
	 * @param string $table 表名称
	 * @return string 返回清空数据表的SQL语句
	 */
	public function getTruncateTable($table)
	{
		$this->connect->execute('DELETE FROM `' . $table . '`');
		$rs = $this->connect->finds('SELECT * FROM `sqlite_sequence`');

		foreach ($rs as $v) {
			if ($v['name'] == $table) {
				$this->connect->execute('CREATE TABLE sqlite_sequence() SET seq=0 WHERE name='.$table);
				break;
			}
		}

		return true;
	}

	public function getDropColumnString($table,$name)
	{
		dpException::error('SQLite数据库系统不允许删除表字段，dpSqliteSchema');
	}

	public function getRenameColumnString($table, $name, $newName)
	{
		dpException::error('SQLite数据库系统不允许重命名表字段，dpSqliteSchema');
	}

	public function getAlertColumn($table, $name, $type)
	{
		dpException::error('SQLite数据库系统不允许更改表字段，dpSqliteSchema');
	}

}